class MyBlockingQueue{
    private String[] elems = null;
    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;

    public MyBlockingQueue(int capacity) {
        elems = new String[capacity];
    }

    void put(String elem) throws InterruptedException {
        //先加锁
        synchronized (this) {
            while (size >= elems.length) {
                //队列满了 ,就要等待
                this.wait();
            }

            //把新的元素放到tail所在的位置上
            elems[tail] = elem;
            tail++;
            if (tail >= elems.length) {
                //到达末尾  ,就回到开头
                tail = 0;
            }
            //更新size的值
            size++;
            //唤醒下面take的wait
            this.notify();
        }
    }

    String take() throws InterruptedException {
        synchronized (this) {
            while (size == 0) {
                //为空要等待
                this.wait();
            }
            //取出 head指向的元素
            String result = elems[head];
            head++;
            if (head >= elems.length) {
                head = 0;
            }

            size--;
            //唤醒put上面的wait
            this.notify();
            return result;
        }

    }
}

public class Text2 {
    //实现一个阻塞队列 模拟一个生产者消费者模型
    public static void main(String[] args) {
        //实例化一个阻塞队列的对象   利用该阻塞队列实现一个生产者消费者模型
        MyBlockingQueue queue = new MyBlockingQueue(1000);

        //生产者线程
        Thread t1 = new Thread(() -> {
            try {
                int count = 0;
                while (true) {
                    queue.put(count + "");
                    System.out.println("生产:" + count);
                    count++;
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //消费者线程
        Thread t2 = new Thread(() ->{
            try {
                while (true) {
                    String result = queue.take();
                    System.out.println("消费:" + result );
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        t2.start();
    }
}
